package cn.lkp.mall.cart.service.impl;

import cn.lkp.common.utils.R;
import cn.lkp.mall.cart.exception.CartExceptionHandler;
import cn.lkp.mall.cart.feign.ProductFeign;
import cn.lkp.mall.cart.interceptor.CartInterceptor;
import cn.lkp.mall.cart.service.CartService;
import cn.lkp.mall.cart.vo.CartVo;
import cn.lkp.mall.cart.vo.CartItemVo;
import cn.lkp.mall.cart.vo.UserInfoTo;
import cn.lkp.mall.cart.vo.SkuInfoVo;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    ProductFeign productFeign;
    @Autowired
    ThreadPoolExecutor executor;
    private final String CART_PREFIX = "mall:cart:";

    /**
     * 根据购物车key获取购物车里面的所有购物项
     * @param
     * @return
     */
    public List<CartItemVo> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItemVo> collect = values.stream().map((obj) -> {
                String s = (String) obj;
                CartItemVo cartItemVo = JSON.parseObject(s, CartItemVo.class);
                return cartItemVo;
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
    /**
     * 选中购物项
     * @param skuId
     * @param checked
     */
    @Override
    public void checkItem(Long skuId, Integer checked){
        //查询购物车里面的商品
        CartItemVo cartItemVo = getCartItem(skuId);
        //修改商品状态
        cartItemVo.setCheck(checked==1?true:false);
        //序列化存入redis中
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    /**
     * 改变购物项的数量
     * @param skuId
     * @param num
     */
    @Override
    public void changeItemCount(Long skuId, Integer num){
        //查询购物车里面的商品
        CartItemVo cartItemVo = getCartItem(skuId);
        //改变购物项的数量
        cartItemVo.setCount(num);
        //序列化存入redis中
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
    }

    /**
     * 删除购物项
     * @param skuId
     */
    @Override
    public void deleteItem(Integer skuId){
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    /**
     * 获取用户登录或者未登录购物车里所有的数据
     * @return
     */
    @Override
    public CartVo getCart() throws ExecutionException, InterruptedException {
        CartVo cart = new CartVo();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()!=null){
            //1.登陆
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            String temptCartKey = CART_PREFIX + userInfoTo.getUserKey();
            //获取临时购物车中的购物项
            List<CartItemVo> tempCartItems = getCartItems(temptCartKey);
            //如果临时购物车中的数据还未进行合并
            if(tempCartItems!=null){
                //临时购物车有数据需要进行合并操作
                for (CartItemVo item : tempCartItems) {
                    addToCart(item.getSkuId(),item.getCount());
                }
                //删除临时购物车
                clearCart(temptCartKey);
            }
            //3、获取登录后的购物车数据【包含合并过来的临时购物车的数据和登录后购物车的数据】
            List<CartItemVo> cartItemVos = getCartItems(cartKey);
            cart.setItems(cartItemVos);
        }else{
            //2.没登陆
            String cartKey = CART_PREFIX + userInfoTo.getUserKey();
            cart.setItems(getCartItems(cartKey));
        }
        return cart;
    }

    /**
     * 清空购物车
     * @param cartKey
     */
    @Override
    public void clearCart(String cartKey){
        redisTemplate.delete(cartKey);
    }

    /**
     * 添加商品到购物车
     * @param skuId
     * @param num
     * @return
     * @throws ExecutionException
     * @throws InterruptedException
     */
    @Override
    public CartItemVo addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        //拿到要操作的购物车信息
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        //判断Redis是否有该商品的信息
        String productRedisValue = (String) cartOps.get(skuId.toString());
        //如果没有就添加数据
        if(StringUtils.isEmpty(productRedisValue)){
            //2.添加新商品到购物车(redis)
            CartItemVo cartItemVo = new CartItemVo();
            //开启第一个异步任务
            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程查询当前要添加的商品信息
                R r = productFeign.info(skuId);
                SkuInfoVo vo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {});
                //数据赋值操作
                cartItemVo.setSkuId(vo.getSkuId());
                cartItemVo.setCount(num);
                cartItemVo.setImage(vo.getSkuDefaultImg());
                cartItemVo.setPrice(vo.getPrice());
                cartItemVo.setTitle(vo.getSkuTitle());
            }, executor);
            //开启第二个异步任务
            CompletableFuture<Void> getSaleAttrValues = CompletableFuture.runAsync(() -> {
                //3.远程查询sku的组合信息
                List<String> saleAttrValues = productFeign.getSaleAttrValues(skuId);
                cartItemVo.setSkuAttrValues(saleAttrValues);
            }, executor);
            //等待所有异步任务执行完毕后再存入redis
            CompletableFuture.allOf(getSkuInfoTask,getSaleAttrValues).get();
            String cartItemJson = JSON.toJSONString(cartItemVo);
            //redis中存储json字符串
            cartOps.put(skuId.toString(),cartItemJson);
            return cartItemVo;
        }else {
            //购物车有此商品，修改数量即可
            CartItemVo cartItemVo = JSON.parseObject(productRedisValue,CartItemVo.class);
            cartItemVo.setCount(cartItemVo.getCount()+num);
            //修改redis的数据
            cartOps.put(skuId.toString(),JSON.toJSONString(cartItemVo));
            return cartItemVo;
        }
    }

    /**
     * 根据指定skuId查询购物车中的某个购物项
     * @param skuId
     * @return
     */
    @Override
    public CartItemVo getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String redisValue = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(redisValue,CartItemVo.class);
    }

    @Override
    public List<CartItemVo> getCurrentCartItems() {
        List<CartItemVo> cartItemVoList = new ArrayList<>();
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if(userInfoTo.getUserId()==null){
            return null;
        }else {
            //如果登录了
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItemVo> cartItemVos = getCartItems(cartKey);
            if(cartItemVos == null){
                throw new CartExceptionHandler();
            }
            //筛选出选中的
            cartItemVoList = cartItemVos.stream().filter(items -> items.getCheck()).map(item -> {
                //查询购物项的最新价格(查数据库)
                BigDecimal price = productFeign.getPrice(item.getSkuId());
                item.setPrice(price);
                return item;
            }).collect(Collectors.toList());
        }
        return cartItemVoList;
    }

    /**
     * 获取到我们要操作的购物车（正式购物车或者临时购物车）
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //先得到当前用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        String cartKey ="";
        if(userInfoTo.getUserId()!=null){
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        }else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }
        //redis中存放购物车信息的数据结构是哈希
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(cartKey);
        return ops;
    }
}
